package com.google.jessewilson.codesearch.io;

import java.net.URI;
import java.net.URISyntaxException;

/**
 * @author jessewilson
 */
public class UriSplicer {

  public String getFileName(URI uri) {
    String path = uri.getPath();
    if(path == null) {
      return "";
    } else {
      return Path.fromString(path).getFileName();
    }
  }

  public URI getParentUri(URI uri) {
    try {
      Path path = Path.fromString(uri.getPath());
      Path parentPath = path.getParent();
      if (parentPath == null) {
        if(path.isAbsolute()) {
          return new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), "/", null, null);
        } else {
          return new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), null, null, null);
        }
      }

      return new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), parentPath.toString(), null, null);
    } catch(URISyntaxException e) {
      return uri;
    }
  }
}
